package com.lry.config;

import com.lry.bean.ExceptionNotice;
import com.lry.enums.DingdingTextType;
import com.lry.httpclient.DefaultDingdingHttpClient;
import com.lry.httpclient.DingdingHttpClient;
import com.lry.properties.DingDingProperties;
import com.lry.send.DingDingNoticeSendComponent;
import com.lry.send.INoticeSendComponent;
import com.lry.text.ExceptionNoticeResolver;
import com.lry.text.markdown.ExceptionNoticeMarkdownMessageResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.gson.Gson;

@Configuration
@ConditionalOnProperty(value = "ea.dingding.enable", havingValue = "true")
@EnableConfigurationProperties({ DingDingProperties.class })
@Slf4j
public class EaDingDingConfig {

	@Bean
	@ConditionalOnMissingBean
	public DingdingHttpClient dingdingHttpClient(DingDingProperties dingDingProperties, Gson gson) {
		DingdingHttpClient dingdingHttpClient = new DefaultDingdingHttpClient(gson, dingDingProperties);
		return dingdingHttpClient;
	}

	@Bean("dingdingSendingComponent")
	@ConditionalOnMissingBean(name = "dingdingSendingComponent")
	public INoticeSendComponent<ExceptionNotice> sendComponent(DingdingHttpClient dingdingHttpClient,
															   ExceptionNoticeResolver exceptionNoticeResolver,
															   DingDingProperties dingDingProperties) {
		log.debug("注册钉钉通知");
		INoticeSendComponent<ExceptionNotice> component = new DingDingNoticeSendComponent
				(dingdingHttpClient, exceptionNoticeResolver, dingDingProperties);
		return component;
	}

	@Bean
	@ConditionalOnMissingBean
	public ExceptionNoticeResolver exceptionNoticeTextResolver(DingDingProperties dingDingProperties) {
		if (dingDingProperties.getDingdingTextType() == DingdingTextType.MARKDOWN)
			return new ExceptionNoticeMarkdownMessageResolver();
		return x -> x.createText();
	}


}
